// extern crate clap;
use clap::{App, Arg};
use hyper::{service, Body, Error, Request, Response, Server};
use std::{env, fs::File, io::Read, net::SocketAddr};
#[tokio::main]
 async fn main() {
   let _matches = App::new("static http server")
   .version("1.0")
   .about("start a static http server")
   .arg(Arg::with_name("port")
   .short("p")
   .long("port")
   .help("Set Server port")
   .default_value("8080")
    ).get_matches();
    let port = _matches.value_of("port").unwrap();
    let addr = SocketAddr::from(([127, 0, 0, 1], port.parse().unwrap()));

    
    run_server(addr).await;

}

/// 处理请求
async fn serve_req(_req: Request<Body>) -> Result<Response<Body>, hyper::Error> {

    let mut path = _req.uri().path();
    match path {
        "/"=>{
            path = "/index.html"
        },
        _ =>{}
    }
    let mut path_string = path.to_string();
    path_string.remove(0);
    println!("路径:{}", path_string);
    let mut full_path = env::current_dir().unwrap();
    full_path = full_path.join(path_string);
    println!("{}", full_path.display());
   
    let contents = read_file(full_path.to_str().unwrap())
    .unwrap_or(String::from("404 Not Found").into_bytes());

    // let mut res = Response::new("马家鹏和沈伟杰肯定是尼玛两个二狗子".into());
    let res = Response::new(contents.into());
    // res.headers_mut()
    //     .insert("Content-Type", "text/html;charset=UTF-8".parse().unwrap());
    Ok(res)
}

/// 启动服务
async fn run_server(addr: SocketAddr) {
    println!("服务器已开启：http://{}", addr);
    let make_serve = service::make_service_fn(|_| async {
        Ok::<_, Error>(service::service_fn(|_req| serve_req(_req)))
    });
    let server = Server::bind(&addr).serve(make_serve);
    let graceful = server.with_graceful_shutdown(shutdown_signal());

    if let Err(e) = graceful.await {
        eprintln!("server error: {}", e);
    }
}

/// 停止服务
async fn shutdown_signal() {
    // Wait for the CTRL+C signal
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install CTRL+C signal handler");
}

/// 读文件
fn read_file(file_path:&str) -> Result<Vec<u8>, &str>{
    let f = File::open(file_path);
    if let  Ok( mut file) = f {

        let mut buffer:Vec<u8> = Vec::new();
        file.read_to_end(& mut buffer).unwrap();
        return Ok(buffer);
    }
 Err("Not Found")

}